package com.sweet.thread;

public class Racing implements Runnable {

    private static String winner;

    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            // 模拟兔子休息 每10米休息一下
            if(Thread.currentThread().getName().equals("兔子") && i != 0 && i%10 == 0) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            if (gameOver(i)) {
              break;
            }
            System.out.println(Thread.currentThread().getName() + "跑了" + i + "米");
        }
    }

    // 判断是否完成了比赛
    private boolean gameOver(int distance) {
        if (winner != null) {
            return true;
        } else {
            if(distance >= 100) {
                winner = Thread.currentThread().getName();
                System.err.println(winner + "赢了比赛");
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Racing r = new Racing();
        new Thread(r,"兔子").start();
        new Thread(r,"乌龟").start();
    }
}
